<template>
  <div
    ref="rellaxItemRef"
    :class="{
      'is-visible': visible
    }"
    class="rellax-item"
    data-rellax-item
    :data-rellax-speed="speed"
  >
    <slot />
  </div>
</template>

<script setup>
import { ref, defineProps, inject, watch } from '@nuxtjs/composition-api'

const props = defineProps({
  speed: {
    type: [String, Number],
    default: -2
  }
})

const rellaxItemRef = ref(null)
const visible = ref(true)

const rellaxRef = inject('rellaxRef')
const positionX = inject('positionX')

const handleVisible = () => {
  const rect = rellaxItemRef.value.getBoundingClientRect()
  const parentRect = rellaxRef.value.getBoundingClientRect()
  const viewLeft = rect.left - parentRect.left

  if (viewLeft >= 0 && rect.right <= parentRect.right) {
    visible.value = true
  } else {
    visible.value = false
  }
}

watch(positionX, (newValue, prevValue) => {
  handleVisible()
})

</script>

<style scoped>
.rellax-item {
  opacity: 0;
  transition: opacity 0.25s;
}
.rellax-item.is-visible {
  opacity: 1;
}
</style>